#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
'''

import sys

sys.path.append('/mnt/moonbrook/Moonbrook')
from aes import contact_aes, name_aes
import os
import re
import json
import time
from hashlib import md5
import requests
from copy import deepcopy
from datetime import datetime, timedelta
from apscheduler.schedulers.blocking import BlockingScheduler

from base import ExportAndTjBase
from models import MongoQueryConfig, RobotConfig
from utils import Utils
from robot import DingtalkRobot

reload(sys)
sys.setdefaultencoding('utf-8')


class ExportAndTj(ExportAndTjBase):
    week_min, week_max = Utils.get_date_range(ndays=7)
    def __init__(self, *args, **kwargs):
        super(ExportAndTj, self).__init__(*args, **kwargs)
        # todo other col
        self.silk_icp_col = self.silk_db.get_collection('icp')

    def get_nameIds_by_ent_name(self,enterprise_name):
        '''
        通过企业名获取nameIds
        @param enterprise_name: 企业名 str
        @return: nameId_ls
        '''
        name_md5 = md5(name_aes.encrypt(enterprise_name)).hexdigest()[8:-8]
        cursor = self.ent_col.find({"nameMd5": name_md5})
        print('{}有{}个nameId'.format(enterprise_name, cursor.count()))
        nameId_ls = []
        for ent_record_dic in cursor:
            nameId = ent_record_dic.get('_id')
            nameId_ls.append(nameId)
        return nameId_ls

    def get_contact_by_ent_name(self, enterprise_name):
        '''
        通过企业名获取所有联系方式
        @param enterprise_name: 企业名称
        @return:
        '''
        phone_ls = []
        for nameId in self.get_nameIds_by_ent_name(enterprise_name):
            if not nameId:
                continue
            print('{}\tnameId：{}'.format(enterprise_name, nameId))
            contact_cursor = self.contact_col.find({'nameId': nameId})
            for contact_record_dic in contact_cursor:
                contact_record_dic = Utils.decrypt_one_record(contact_record_dic, need_decrypt=True)
                _contact = contact_record_dic.get('contact')
                _contact_type = contact_record_dic.get('contactType')
                if _contact_type in ['0',0]:
                    if _contact:
                        phone_ls.append(_contact)
        return phone_ls


    def run(self):
        for name in ['lxy','jzy','xk','jxs','kzz','qd']:
            print('{} start ========'.format(name))
            path = '/tmp/dsf/result_{}.json'.format(name)
            if not os.path.exists(path):
                print(path,' not exists')
                continue
            with open(path,'r') as f:
                self.result = json.load(f)
            self.real_result = {}
            for ent_name,dic in self.result.items():
                ent_name = ent_name.strip().replace('（','(').replace('）',')')
                phone_ls = self.get_contact_by_ent_name(ent_name)
                print('探迹：{}'.format(phone_ls))
                self.real_result[ent_name] = {
                    'start_year':dic.get('start_year'),
                    'ys_phone_count':dic.get('phone_count'),
                    'tj_phone_count':len(phone_ls),
                    'phone_ls':[]
                }
                for phone_dic in dic.get('phone_ls',[]):
                    if phone_dic.get('phone') not in phone_ls:
                        self.real_result[ent_name]['phone_ls'].append(phone_dic)


            with open('/tmp/dsf/real/result_{}.json'.format(name),'w') as f:
                json.dump(self.real_result,f,ensure_ascii=False,indent=4)
            print('{} end ========'.format(name))






def run(file_name):
    # py文件名/file_name+小时时间
    abs_file_name = Utils.generate_abs_path(file_name, current_py_path=__file__)
    export_and_tj = ExportAndTj(abs_file_name)
    export_and_tj.main()


def scheduler_run(file_name):
    # py文件名/file_name+小时时间
    abs_file_name = Utils.generate_abs_path(file_name, current_py_path=__file__)
    scheduler = BlockingScheduler()
    scheduler.add_job(func=run, trigger='cron',
                      args=(abs_file_name,),
                      # day_of_week="sun",
                      hour='20', minute='52', id='dd_run')
    scheduler.start()


if __name__ == '__main__':
    file_name = '官网统计'
    run(file_name)
    # scheduler_run(file_name)
